package container

import (
	"adai.design/homemaster/container/accessory"
	"errors"
)


type Container struct {
	Id 			string					`json:"id"`
	Version 	int						`json:"version"`
	Accessories []*accessory.Accessory	`json:"accessories"`
	versionChangeFuncs 	[]func(new, old int)
}

func NewContainer() *Container {
	return &Container{
		Version: 5,
		Accessories: make([]*accessory.Accessory, 0),
	}
}

// container 版本变化
func (c *Container) OnVersionChange(fn func(new, old int)) error {
	exist := false
	for _, v := range c.versionChangeFuncs {
		if &v == &fn {
			exist = true
		}
	}
	if !exist {
		c.versionChangeFuncs = append(c.versionChangeFuncs, fn)
	}
	return nil
}

func (c *Container) SetVersion(version int) {
	old := c.Version
	if old != version {
		c.Version = version
		for _, fn := range c.versionChangeFuncs {
			fn(version, old)
		}
	}
}

func (c *Container) AddAccessory(a *accessory.Accessory) error {
	for _, v := range c.Accessories {
		if v.UUID == a.UUID {
			return errors.New("accessory already exists")
		}
	}

	c.Accessories = append(c.Accessories, a)
	return nil
}

func (c *Container) RemoveAccessory(a *accessory.Accessory) error {
	for i, v := range c.Accessories {
		if a.UUID == v.UUID {
			c.Accessories = append(c.Accessories[:i], c.Accessories[i+1:]...)
			return nil
		}
	}
	return errors.New("accessory does not exits")
}

